﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;

namespace Reporting
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string[] dumpArray = System.IO.File.ReadAllText(Application.StartupPath + "//log_dumps.txt").Split('\n'); //Seperates dumps by ~
        string[] db = System.IO.File.ReadAllLines(Application.StartupPath + "//db.csv");

        


        private void Form1_Load(object sender, EventArgs e)
        {
            //Reads through database, checks for item's existance. Adds items to combobox
            comboBox2.SelectedIndex = 0;
            for (int i = 0; i < db.Length; i++)
            {
                for (int f = 0; f < dumpArray.Length; f++)
                {
                   
                    if (db[i].Split(',')[0] == dumpArray[f].Split(',')[0])
                    {
                        bool alreadyExists = false;
                        for (int b = 0; b < comboBox1.Items.Count; b++)
                        {
                            if (db[i].Split(',')[0] == comboBox1.Items[b].ToString())
                            {
                                alreadyExists = true;
                            }
                            
                        }
                        if (alreadyExists == false)
                        {
                            comboBox1.Items.Add(db[i].Split(',')[0]);
                        }

                    }
                }
            }
            comboBox1.SelectedIndex = 0;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Variables for Sales
            List<String> mylist = new List<string>();
            double price = 0;
            double cost = 0;
            int sold = 0;
            //Adds Two Items to Get Total
            for (int f = 0; f < dumpArray.Length; f++)
            {

                if (comboBox1.SelectedItem.ToString() == dumpArray[f].Split(',')[0])
                {
                    cost = cost + (System.Convert.ToDouble(dumpArray[f].Split(',')[3]) * System.Convert.ToDouble(dumpArray[f].Split(',')[1]));
                    price = price + (System.Convert.ToDouble(dumpArray[f].Split(',')[4]) * System.Convert.ToDouble(dumpArray[f].Split(',')[1]));
                    sold = sold + (System.Convert.ToInt32(dumpArray[f].Split(',')[1]));
                }
                else if (comboBox1.SelectedItem.ToString() == "Total")
                {
                    try
                    {
                        cost = cost + (System.Convert.ToDouble(dumpArray[f].Split(',')[3]) * System.Convert.ToDouble(dumpArray[f].Split(',')[1]));
                        price = price + (System.Convert.ToDouble(dumpArray[f].Split(',')[4]) * System.Convert.ToDouble(dumpArray[f].Split(',')[1]));
                        sold = sold + (System.Convert.ToInt32(dumpArray[f].Split(',')[1]));
                    }
                    catch { }
                }
            }
            //Makes Label Text to String Format
            label2.Text = String.Format("{0:C}", cost);
            label3.Text = String.Format("{0:C}", price);
            label4.Text = String.Format("{0:C}", price - cost);
            label5.Text = (Math.Round(((price - cost) / cost) * 100)).ToString() + "%";
            label10.Text = String.Format("{0:C}", (price * 0.06));
            label11.Text = sold.ToString();

            if (comboBox1.SelectedItem.ToString() != "Total")
            {
                string amount = ""; 
                for (int i = 0; i < db.Length; i++)
                {
                    if (db[i].Split(',')[0] == comboBox1.SelectedItem.ToString())
                    {
                        amount = db[i].Split(',')[2];
                        
                    }
                }
                //Updates the Amount Label and Shows what Steps to Use
                label12.Text = amount.ToString();
                double remainingPercent = (Math.Round((System.Convert.ToDouble(amount) / (sold + System.Convert.ToDouble(amount))) * 100));
                label14.Text = remainingPercent.ToString() + "%";
                trackBar1.Value = System.Convert.ToInt32(remainingPercent);
                if (remainingPercent <= 50 && remainingPercent > 27)
                {
                    label13.Text = "Item running low.";
                    label13.ForeColor = Color.Orange;
                    label13.Visible = true;
                }
                else if (remainingPercent <= 27)
                {
                    label13.Text = "Add inventory immediately.";
                    label13.ForeColor = Color.Red;
                    label13.Visible = true;
                }
                else if (remainingPercent > 50)
                {
                    label13.Text = "OK.";
                    label13.ForeColor = Color.LightGreen;
                    label13.Visible = true;
                    
                }
            }
            else
            {
            //Put Systems to Int, Double Remaining Percent

                label13.Visible = false;
                int total = 0;
                for (int i = 0; i < db.Length; i++)
                {
                    total = total + System.Convert.ToInt32(label12.Text = db[i].Split(',')[2]);
                }
                label12.Text = total.ToString();
                double remainingPercent = (Math.Round((System.Convert.ToDouble(total) / (sold + System.Convert.ToDouble(total))) * 100));
                label14.Text = remainingPercent.ToString() + "%";
                trackBar1.Value = System.Convert.ToInt32(remainingPercent);
                //label14.Text = (Math.Round((System.Convert.ToDouble(total) / (sold + System.Convert.ToDouble(total))) * 100)).ToString() + "%";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Choose Print selection
            if (comboBox2.SelectedIndex == -1)
            {
                MessageBox.Show("Select your print selection.");
            }
            else
            {
                if (printDialog1.ShowDialog() == DialogResult.OK)
                {
                    
                    printDocument1.Print();
                }

            }
            
        }

        public string printString()
        {
            //Return Print String
            if (comboBox2.SelectedIndex == 0)
            {
                return gatherPrintString(comboBox1.SelectedIndex, comboBox1.SelectedIndex);
            }
            else
            {
                return gatherPrintString(0, comboBox1.Items.Count - 1);
            }
        }

        public string gatherPrintString(int page, int count)
        {
            //Determines Size of Separations
            string list = "";
            for (int i = page; i <= count; i++)
            {
                string nl = Environment.NewLine;
                string nlPadding = nl + nl;
                string catSep = " --------------";
                string largeSep = "________________________";
                if (i == page)
                {
                    largeSep = string.Empty;
                    nlPadding = string.Empty;
                }
                comboBox1.SelectedIndex = i;
                //Where Text Shows Up at
                list = list + string.Join(nl, new string[] { 
                    nlPadding + largeSep + nlPadding + comboBox1.Text.ToUpper(),
                    catSep,
                    "     Cost: " + label2.Text,
                    "     Price: " + label3.Text,
                    catSep,
                    "  - Profit -",
                    "     Dollars: " + label4.Text,
                    "     Percent: " + label5.Text,
                    catSep,
                    "     Sales Tax: " + label10.Text,
                    catSep,
                    "  - Stock -",
                    "     Sold: " + label11.Text,
                    "     Remaining: " + label12.Text
                });
            }
            return list;
        }

        private int linesPrinted;
        private string[] lines;

        private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
        {
            //How Large To Print
            char[] param = { '\n' };

            if (printDialog1.PrinterSettings.PrintRange == PrintRange.Selection)
            {
                lines = printString().Split(param);
            }
            else
            {
                lines = printString().Split(param);
            }

            int i = 0;
            char[] trimParam = { '\r' };
            foreach (string s in lines)
            {
                lines[i++] = s.TrimEnd(trimParam);
            }
        }

        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            //Where to Start Printing, And Format
            int x = e.MarginBounds.Left;
            int y = e.MarginBounds.Top;

            while (linesPrinted < lines.Length)
            {
                e.Graphics.DrawString(lines[linesPrinted++],
                    new Font("Lucida Console", 10, FontStyle.Regular), new SolidBrush(Color.Green), x, y);
                y += 15;
                if (y >= e.MarginBounds.Bottom)
                {
                    e.HasMorePages = true;
                    return;
                }
            }

            linesPrinted = 0;
            e.HasMorePages = false;
        }

    }
}
